package com.business.dashboard.controller;

import com.business.dashboard.entity.NewsArticle;
import com.business.dashboard.service.NewsArticleService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 管理员新闻管理控制器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/news")
@Validated
public class AdminNewsController {

    @Autowired
    private NewsArticleService newsArticleService;

    /**
     * 获取所有新闻文章
     */
    @GetMapping("")
    public ResultUtil<List<NewsArticle>> getAllNews() {
        try {
            List<NewsArticle> newsList = newsArticleService.getAllNews();
            return ResultUtil.success("获取新闻列表成功", newsList);
        } catch (Exception e) {
            log.error("获取新闻列表失败，", e);
            return ResultUtil.error("获取新闻列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取新闻文章
     */
    @GetMapping("/{id}")
    public ResultUtil<NewsArticle> getNewsById(
                                              @PathVariable @NotNull Long id) {
        try {
            NewsArticle news = newsArticleService.getNewsById(id);
            if (news != null) {
                return ResultUtil.success("获取新闻详情成功", news);
            } else {
                return ResultUtil.error(404, "新闻不存在");
            }
        } catch (Exception e) {
            log.error("获取新闻详情失败，newsId: {}", id, e);
            return ResultUtil.error("获取新闻详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建新闻文章
     */
    @PostMapping("")
    public ResultUtil<NewsArticle> createNews(
                                             @RequestBody @Valid NewsArticle news,
                                             HttpServletRequest request) {
        try {
            // 设置作者信息
            String adminUsername = (String) request.getSession().getAttribute("adminUsername");
            Object adminIdObj = request.getSession().getAttribute("adminId");
            Long adminId = adminIdObj != null ? (Long) adminIdObj : 1L;
            news.setAuthorId(adminId);
            news.setAuthorName(adminUsername != null ? adminUsername : "管理员");

            NewsArticle createdNews = newsArticleService.createNews(news);
            return ResultUtil.success("创建新闻成功", createdNews);
        } catch (Exception e) {
            log.error("创建新闻失败，", e);
            return ResultUtil.error("创建新闻失败：" + e.getMessage());
        }
    }

    /**
     * 更新新闻文章
     */
    @PutMapping("/{id}")
    public ResultUtil<NewsArticle> updateNews(
                                             @PathVariable @NotNull Long id,
                                             @RequestBody @Valid NewsArticle news) {
        try {
            news.setId(id);
            NewsArticle updatedNews = newsArticleService.updateNews(news);
            return ResultUtil.success("更新新闻成功", updatedNews);
        } catch (Exception e) {
            log.error("更新新闻失败，newsId: {}", id, e);
            return ResultUtil.error("更新新闻失败：" + e.getMessage());
        }
    }

    /**
     * 删除新闻文章
     */
    @DeleteMapping("/{id}")
    public ResultUtil<String> deleteNews(
                                        @PathVariable @NotNull Long id) {
        try {
            boolean deleted = newsArticleService.deleteNews(id);
            if (deleted) {
                return ResultUtil.success("删除新闻成功");
            } else {
                return ResultUtil.error("删除新闻失败");
            }
        } catch (Exception e) {
            log.error("删除新闻失败，newsId: {}", id, e);
            return ResultUtil.error("删除新闻失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新新闻状态
     */
    @PutMapping("/batch/status")
    public ResultUtil<String> batchUpdateStatus(
                                               @RequestParam List<Long> ids,
                                               @RequestParam String status) {
        try {
            boolean updated = newsArticleService.batchUpdateStatus(ids, status);
            if (updated) {
                return ResultUtil.success("批量更新状态成功");
            } else {
                return ResultUtil.error("批量更新状态失败");
            }
        } catch (Exception e) {
            log.error("批量更新新闻状态失败，", e);
            return ResultUtil.error("批量更新状态失败：" + e.getMessage());
        }
    }

    /**
     * 发布新闻
     */
    @PutMapping("/{id}/publish")
    public ResultUtil<String> publishNews(
                                         @PathVariable @NotNull Long id) {
        try {
            boolean published = newsArticleService.publishNews(id);
            if (published) {
                return ResultUtil.success("发布新闻成功");
            } else {
                return ResultUtil.error("发布新闻失败");
            }
        } catch (Exception e) {
            log.error("发布新闻失败，newsId: {}", id, e);
            return ResultUtil.error("发布新闻失败：" + e.getMessage());
        }
    }

    /**
     * 取消发布新闻
     */
    @PutMapping("/{id}/unpublish")
    public ResultUtil<String> unpublishNews(
                                           @PathVariable @NotNull Long id) {
        try {
            boolean unpublished = newsArticleService.unpublishNews(id);
            if (unpublished) {
                return ResultUtil.success("取消发布成功");
            } else {
                return ResultUtil.error("取消发布失败");
            }
        } catch (Exception e) {
            log.error("取消发布新闻失败，newsId: {}", id, e);
            return ResultUtil.error("取消发布失败：" + e.getMessage());
        }
    }

    /**
     * 获取新闻统计数据
     */
    @GetMapping("/stats")
    public ResultUtil<Object> getNewsStats() {
        try {
            Object stats = newsArticleService.getNewsStats();
            return ResultUtil.success("获取新闻统计成功", stats);
        } catch (Exception e) {
            log.error("获取新闻统计失败，", e);
            return ResultUtil.error("获取新闻统计失败：" + e.getMessage());
        }
    }
}